﻿using System;
using System.Diagnostics;

namespace CSUploadOSUI
{
    internal class LineCommandProcess
    {

        private readonly Process _command;

        internal LineCommandProcess(CsUploadTool sqlmetal, DataReceivedEventHandler dataReceivedEventHandler)
        {
            _command =
                new Process
                    {
                        EnableRaisingEvents = true,
                        StartInfo =
                            {
                                WindowStyle = ProcessWindowStyle.Hidden,
                                CreateNoWindow = true,
                                RedirectStandardOutput = true,
                                RedirectStandardInput = false,
                                UseShellExecute = false,
                                FileName = sqlmetal.Path
                            }
                    };

            _command.OutputDataReceived += dataReceivedEventHandler;
            _command.Exited += _command_Exited;
        }

        void _command_Exited(object sender, EventArgs e)
        {
            _command.CancelOutputRead();
        }

        internal string ExecuteWithParameters(string parameters)
        {
            try
            {
                _command.StartInfo.Arguments = parameters;
                _command.Start();
                return _command.StandardOutput.ReadToEnd();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        internal void ExecuteAsyncWithParameters(string parameters)
        {
            try
            {
                _command.StartInfo.Arguments = parameters;
                _command.Start();
                _command.BeginOutputReadLine();
            }
            catch (Exception ex)
            {
                //return ex.Message;
            }

        }

        internal string ExecuteWithNoParameters()
        {
            try
            {
                
                _command.Start();
                return _command.StandardOutput.ReadToEnd();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        internal string ExecuteForInformationPruposes()
        {
            string result;

            try
            {
                _command.Start();
                //only takes the 3 first lines
                result = _command.StandardOutput.ReadLine() + "\r\n";
                result += _command.StandardOutput.ReadLine() + "\r\n";
                result += _command.StandardOutput.ReadLine();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            return result;

        }

    }

}
